<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作类型" prop="operateType">
        <el-select v-model="queryParams.operateType" placeholder="请选择操作类型" clearable>
          <!-- 搜索下拉框显示“入库/出库”，实际值为1/2 -->
          <el-option key="1" label="入库" value="1" />
          <el-option key="2" label="出库" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="operateTime">
        <el-date-picker clearable
          v-model="queryParams.operateTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['material:operate:add']"
        >进货</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['material:operate:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="operateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="操作id" align="center" prop="operateId" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="物资名称" align="center" prop="materialName" />
      <el-table-column label="操作类型" align="center" prop="operateType">
        <template slot-scope="scope">
          <!-- 根据值1/2转换为“入库/出库”显示 -->
          <span>{{ scope.row.operateType === 1 ? '入库' : '出库' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作数量" align="center" prop="quantity" />
      <el-table-column label="操作时间" align="center" prop="operateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['material:operate:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改后的进货对话框 -->
    <el-dialog title="进货操作" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="仓库" prop="warehouse">
          <el-select v-model="form.warehouse" placeholder="请选择仓库" clearable style="width: 100%">
            <el-option
              v-for="warehouse in warehouseList"
              :key="warehouse.warehouseId"
              :label="warehouse.warehouseName"
              :value="warehouse.warehouseId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物资" prop="material">
          <el-select v-model="form.material" placeholder="请选择物资" clearable style="width: 100%">
            <el-option
              v-for="material in materialList"
              :key="material.materialId"
              :label="material.materialName"
              :value="material.materialId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型" prop="operateType">
          <!-- 进货默认操作类型为1（入库），禁用选择 -->
          <el-select v-model="form.operateType" placeholder="入库" disabled clearable style="width: 100%">
            <el-option label="入库" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="进货数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="1" placeholder="进货数量" style="width: 100%"></el-input-number>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"
            :autosize="{minRows: 4, maxRows: 4}" style="width: 100%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 出货对话框 -->
    <el-dialog title="出货操作" :visible.sync="outputOpen" width="500px" append-to-body @close="onOutputClose">
      <el-form ref="outputForm" :model="outputForm" :rules="outputRules" size="medium" label-width="100px">
        <el-form-item label="仓库" prop="warehouse">
          <el-select v-model="outputForm.warehouse" placeholder="请选择仓库" clearable style="width: 100%">
            <el-option
              v-for="(item, index) in warehouseOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物资" prop="material">
          <el-select v-model="outputForm.material" placeholder="请选择物资" clearable style="width: 100%">
            <el-option
              v-for="(item, index) in materialOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型" prop="operateType">
          <!-- 出货默认操作类型为2（出库），禁用选择 -->
          <el-select v-model="outputForm.operateType" placeholder="出库" disabled clearable style="width: 100%">
            <el-option label="出库" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库数量" prop="quantity">
          <el-input-number v-model="outputForm.quantity" :min="1" placeholder="出库数量" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="当前库存" prop="currentStock">
          <el-input v-model="outputForm.currentStock" placeholder="当前库存数量" readonly clearable style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="领用部门" prop="department">
          <el-input v-model="outputForm.department" placeholder="请输入领用部门" clearable style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="outputForm.remark" type="textarea" placeholder="请输入备注"
            :autosize="{minRows: 4, maxRows: 4}" style="width: 100%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="outputOpen = false">取消</el-button>
        <el-button type="primary" @click="handleOutputConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOperate, getOperate, delOperate, addOperate, updateOperate } from "@/api/material/operate"
import { listInfo } from "@/api/material/info"
import { listMaterial_warehouse } from "@/api/material/material_warehouse"

export default {
  name: "Operate",
  dicts: ['operation_type'],
  data() {
    return {
      materialList: [],
      warehouseList: [],
      loadAllParams: {
        pageNum: 1,
        pageSize: 10000,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 操作记录模块表格数据
      operateList: [],
      // 弹出层标题
      title: "",
      // 是否显示进货弹出层
      open: false,
      // 是否显示出货弹出层
      outputOpen: false, // 添加这个变量控制出货对话框显示
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseName: null,
        materialName: null,
        operateType: null,
        operateTime: null,
      },
      // 进货表单参数
      form: {
        warehouse: undefined,
        material: undefined,
        operateType: 1,
        quantity: undefined,
        supplier: undefined,
        remark: undefined,
        warehouseName: null,
        materialName: null,
        materialId: null,
        warehouseId: null

      },

      // 出货表单参数
      outputForm: {
        warehouse: undefined,
        material: undefined,
        operateType: '出库',
        quantity: undefined,
        currentStock: undefined,
        department: undefined,
        remark: undefined,
      },
      // 进货表单校验
       // 进货表单校验
       rules: {
        warehouse: [{
          required: true,
          message: '请选择仓库',
          trigger: 'change'
        }],
        material: [{
          required: true,
          message: '请选择物资',
          trigger: 'change'
        }],
        quantity: [{
          required: true,
          message: '请输入进货数量',
          trigger: 'blur'
        }],
        supplier: [{
          required: true,
          message: '请输入供应商',
          trigger: 'blur'
        }],
      },

      // 出货表单校验
      outputRules: {
        warehouse: [{
          required: true,
          message: '请选择仓库',
          trigger: 'change'
        }],
        material: [{
          required: true,
          message: '请选择物资',
          trigger: 'change'
        }],
        quantity: [{
          required: true,
          message: '请输入出库数量',
          trigger: 'blur'
        }],
        department: [{
          required: true,
          message: '请输入领用部门',
          trigger: 'blur'
        }],
      },
      // 进货操作类型选项
      inputOperateTypeOptions: [
        { label: "进货", value: "进货" }
      ],
      // 仓库选项
      warehouseOptions: [
        { label: "仓库1", value: "仓库1" },
        { label: "仓库2", value: "仓库2" }
      ],
      // 物资选项
      materialOptions: [
        { label: "物资1", value: "物资1" },
        { label: "物资2", value: "物资2" }
      ],
      // 操作类型选项
      operateTypeOptions: [
        { label: "出库", value: "出库" }
      ]
    }
  },
  created() {
    this.getList(),
    this.getMaterialNameList(),
    this.getWarehouse()
  },
  methods: {

    getWarehouse(){
      this.loading = true;
      listMaterial_warehouse(this.loadAllParams).then((response) => {
        this.warehouseList = response.rows;
        this.loading = false;
      });
    },

    /** 下拉框物资列表 */
    getMaterialNameList() {
      this.loading = true;
      listInfo(this.loadAllParams).then((response) => {
        this.materialList = response.rows;
        this.loading = false;
      });
    },

    /** 查询操作记录模块列表 */
    getList() {
      this.loading = true
      listOperate(this.queryParams).then(response => {
        this.operateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        operateId: null,
        warehouseName: null,
        materialName: null,
        operateType: null,
        quantity: null,
        operateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    // 出货表单重置
    resetOutputForm() {
      this.outputForm = {
        warehouse: undefined,
        material: undefined,
        operateType: '出库',
        quantity: undefined,
        currentStock: undefined,
        department: undefined,
        remark: undefined,
      }
      if (this.$refs.outputForm) {
        this.$refs.outputForm.resetFields()
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.operateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加操作记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const operateId = row.operateId || this.ids
      getOperate(operateId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改操作记录"
      })
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.operateId != null) {
    //         updateOperate(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       } else {
    //         addOperate(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       }
    //     }
    //   })
    // },

    /** 提交按钮 */
  submitForm() {
    this.$refs["form"].validate(valid => {
      if (valid) {
        // 构建与后端实体类匹配的请求数据
        // console.log(materialId)
        console.log(this.form.material)
        console.log(this.form.warehouse)

        const submitData = {
          // 仓库ID（前端form.warehouse绑定的是仓库ID，直接对应后端warehouseId）
          warehouseId: this.form.warehouse,
          // 物资ID（前端form.material绑定的是物资ID，直接对应后端materialId）
          materialId: this.form.material,
          // 操作类型（确保值与后端字典一致，例如“进货”对应字典值“1”，需确认后端定义）
          operateType: 1, // 若后端需要字典值，需改为具体值（如"1"）
          // 数量（前端form.quantity已正确绑定）
          quantity: this.form.quantity,
          // 操作时间（当前时间，格式需与后端匹配，如yyyy-MM-dd HH:mm:ss）
          operateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
          // 备注（前端form.remark已正确绑定）
          remark: this.form.remark,
        };

        // 调用新增接口（注意：你的代码中之前混用了updateOperate，这里进货只需调用addOperate）
        addOperate(submitData).then(response => {
          this.$modal.msgSuccess("进货成功");
          this.open = false;
          this.getList(); // 刷新列表
        }).catch(error => {
          console.error("进货失败：", error);
          this.$modal.msgError("提交失败，请重试");
        });
      }
    });
  },

    /** 出货按钮操作 */
    handleOutput() {
      this.resetOutputForm()
      this.outputOpen = true // 打开出货对话框
    },
    // 出货弹框关闭回调
    onOutputClose() {
      this.resetOutputForm()
    },
    // 出货确认
    handleOutputConfirm() {
      this.$refs["outputForm"].validate(valid => {
        if (valid) {
          // 这里应该调用出货API
          // 假设有一个outputMaterial API
          // outputMaterial(this.outputForm).then(response => {
          //   this.$modal.msgSuccess("出货成功")
          //   this.outputOpen = false
          //   this.getList()
          // })

          // 暂时模拟成功
          this.$modal.msgSuccess("出货成功")
          this.outputOpen = false
          this.getList()
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const operateIds = row.operateId || this.ids
      this.$modal.confirm('是否确认删除操作记录模块编号为"' + operateIds + '"的数据项？').then(function() {
        return delOperate(operateIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('material/operate/export', {
        ...this.queryParams
      }, `operate_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
